<!--src/views/auth/LoginView.vue-->
<template>
  <div class="login-wrapper">
    <div class="legal-pattern"></div>
    <div class="login-card">
      <div class="logo-container">
        <h1>法律援助平台</h1>
        <p class="slogan">公正 · 专业 · 高效</p>
      </div>

      <div class="login-tabs">
        <button
            :class="['tab', { active: loginType === 'password' }]"
            @click="loginType = 'password'">
          密码登录
        </button>
        <button
            :class="['tab', { active: loginType === 'code' }]"
            @click="loginType = 'code'">  <!-- 修正这里：loginType 而不是 login -->
          验证码登录
        </button>
    </div>

    <form @submit.prevent="handleLogin" class="login-form">
      <!-- 密码登录使用用户名输入框 -->
      <div v-if="loginType === 'password'" class="form-group">
        <label for="username">
          <i class="icon-user"></i> 用户名
        </label>
        <input
            type="text"
            id="username"
            v-model.trim="form.username"
            placeholder="请输入用户名"
            @input="clearError"
        />
      </div>

      <!-- 验证码登录使用手机号输入框 -->
      <div v-else class="form-group">
        <label for="phone">
          <i class="icon-phone"></i> 手机号
        </label>
        <input
            type="tel"
            id="phone"
            v-model.trim="form.phone"
            placeholder="请输入手机号"
            @input="clearError"
        />
      </div>

      <!-- 密码登录表单 -->
      <div v-if="loginType === 'password'" class="form-group">
        <label for="password">
          <i class="icon-lock"></i> 密码
        </label>
        <input
            type="password"
            id="password"
            v-model.trim="form.password"
            placeholder="请输入密码"
            @input="clearError"
        />
      </div>

      <!-- 验证码登录表单 -->
      <div v-else class="form-group">
        <label for="code">
          <i class="icon-code"></i> 验证码
        </label>
        <div class="code-input-wrapper">
          <input
              type="text"
              id="code"
              v-model.trim="form.code"
              placeholder="请输入验证码"
              @input="clearError"
          />
          <button
              type="button"
              class="send-code-btn"
              :disabled="isSending"
              @click="sendCode">
            {{ isSending ? `${countdown}秒后重发` : '获取验证码' }}
          </button>
        </div>
      </div>

      <div v-if="errorMessage" class="error-message">
        <i class="icon-warning"></i> {{ errorMessage }}
      </div>

      <button type="submit" class="login-btn" :disabled="isLoading">
        <i class="icon-login" v-if="!isLoading"></i>
        <i class="icon-loading" v-else></i>
        <span>{{ isLoading ? '登录中...' : '登 录' }}</span>
      </button>
    </form>

    <div class="footer-links">
      <router-link to="/register">
        <i class="icon-register"></i> 注册账号
      </router-link>
      <span class="divider">|</span>
      <router-link to="/forgot-password">
        <i class="icon-forgot"></i> 忘记密码
      </router-link>
    </div>
  </div>
  </div>
</template>

<script>
import { useAuthStore } from '@/stores/modules/authStore'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import "@/styles/loginview.css"
import http from "@/axios/index.js";

export default {
  name: 'LoginView',
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()

    const loginType = ref('password')
    const form = ref({
      username: '',
      phone: '',
      password: '',
      phoneCode: '123456' // 默认验证码，方便测试
    })
    const errorMessage = ref('')
    const isLoading = ref(false)
    const isSending = ref(false)
    const countdown = ref(60)

    const clearError = () => {
      errorMessage.value = ''
    }

    const sendCode = async () => {
      if (!form.value.phone) {
        errorMessage.value = '请输入手机号'
        return
      }

      isSending.value = true
      try {
        // 这里应该调用发送验证码的API
        // await authStore.sendVerificationCode(form.value.phone)

        ElMessage.success('验证码已发送：123456')

        // 倒计时逻辑
        const timer = setInterval(() => {
          if (countdown.value <= 0) {
            clearInterval(timer)
            isSending.value = false
            countdown.value = 60
            return
          }
          countdown.value--
        }, 1000)
      } catch (error) {
        ElMessage.error(error.message || '发送验证码失败')
        isSending.value = false
      }
    }

    const handleLogin = async () => {
      isLoading.value = true
      errorMessage.value = ''

      try {
        console.log('提交的登录数据:', form.value)
        let response

        if (loginType.value === 'password') {
          // 密码登录
          response = await authStore.loginByPassword(
            form.value.username,
            form.value.password
        )
          console.log('API原始响应:', response)

        } else {
          // 验证码登录
          response = await userAPI.loginByCode(form.value.phone, form.value.code)
        }
        // 在这里输出response
        console.log('完整的response对象:', response)

        // 检查登录是否成功
        if (response.success) {
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          throw new Error(response.error || '登录失败')
        }
      } catch (err) {
        console.error('登录错误:', err)
        errorMessage.value = err.message || '登录失败，请检查用户名和密码'
        ElMessage.error(errorMessage.value)
      } finally {
        isLoading.value = false
      }
    }

    return {
      loginType,
      form,
      errorMessage,
      isLoading,
      isSending,
      countdown,
      clearError,
      sendCode,
      handleLogin,
      router
    }
  }
}
</script>

<style scoped>
/* 新增登录选项卡样式 */
.login-tabs {
  display: flex;
  margin-bottom: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.tab {
  flex: 1;
  padding: 0.8rem 0;
  background: none;
  border: none;
  font-size: 1rem;
  font-weight: 500;
  color: #718096;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.tab.active {
  color: #4299e1;
  font-weight: 600;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 3px;
  background: #4299e1;
  border-radius: 3px 3px 0 0;
}

/* 验证码输入区域样式 */
.code-input-wrapper {
  display: flex;
  gap: 10px;
}

.code-input-wrapper input {
  flex: 1;
}

.send-code-btn {
  min-width: 120px;
  padding: 0.9rem 0.5rem;
  background-color: #edf2f7;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
}

.send-code-btn:hover:not(:disabled) {
  background-color: #e2e8f0;
}

.send-code-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

/* 新增手机图标样式 */
.icon-phone {
  width: 16px;
  height: 16px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%234a5568"><path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.1-.03-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"/></svg>') no-repeat;
}

.icon-code {
  width: 16px;
  height: 16px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%234a5568"><path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V8h16v10zm-8-2c0 .55-.45 1-1 1s-1-.45-1-1v-2H8c-.55 0-1-.45-1-1s.45-1 1-1h2v-2c0-.55.45-1 1-1s1 .45 1 1v2h2c.55 0 1 .45 1 1s-.45 1-1 1h-2v2z"/></svg>') no-repeat;
}

/* 其他保持原有样式不变 */

/* 全局样式重置 */
html, body, #app {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

</style>